#pragma strict
var speed : float;
var player : Transform;
var childTransform : Transform;
var child : Child;
var mainTexture : Texture;
var damageTexture : Texture;
private var mainRenderer : Renderer;
var timeToChangeDirection : float = 4;
var isMoving : boolean = false;
var isAttacking : boolean = false;

var hittingSFX : AudioClip;
var hittedSFX : AudioClip;

function Start ()
{
	mainRenderer = GetComponentInChildren(Renderer);
	isMoving = false;
	speed = 25;
	yield WaitForSeconds (1);
	mainRenderer.material.mainTexture = mainTexture;
	isMoving = true;
}

function Update ()
{
	timeToChangeDirection -= Time.deltaTime;
	if (timeToChangeDirection < 0)
	{
		speed *= -1;
		timeToChangeDirection = Random.Range(0,8);
	}
	if (childTransform)
	{
		if (Mathf.Abs(childTransform.position.x - transform.position.x) < 5)
			Attack ();
	}
	if (speed > 0)
		transform.rotation.y = 0;
	if (speed < 0)
		transform.rotation.y = 1;
		
	if (isMoving)
		transform.Translate(-speed *Time.deltaTime,0,0, Space.World);
}

function Attack ()
{
	timeToChangeDirection += 1;
	if (isMoving)
		isAttacking = true;
		
	if (isAttacking)
	{
		isAttacking = false;
		isMoving = false;
		if (speed < 0)
		{
			iTween.RotateTo(gameObject,{"z":90, "time": 0.4});
		}
		if (speed > 0)
		{
			iTween.RotateTo(gameObject,{"z":90, "time": 0.4});
		}
		iTween.RotateTo(gameObject,{"z":0, "delay":0.4, "time":0.4});

		audio.PlayOneShot(hittingSFX);
		child.Attacked ();
		yield WaitForSeconds(1);
		isMoving = true;
	}
}

function Attacked ()
{
	if (isAttacking)
		return;
	if (Mathf.Abs(transform.position.x - player.position.x) < 10)
	{
		audio.PlayOneShot(hittedSFX);
		mainRenderer.material.mainTexture = damageTexture;
		isMoving = false;
		timeToChangeDirection += 1;
		yield WaitForSeconds(1);
		isMoving = true;
		mainRenderer.material.mainTexture = mainTexture;
		speed *= -1;
	}
}